using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ent.Voice.Show;
using System.Collections.Generic;
using Ent.Web.Helper;
using Ent.Voice.Nomination;
using System.Text.RegularExpressions;

public partial class Controls_Nomination_Upload : Ent.Web.WebControl.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblContent.Text = ResourceHelper.Get("LBL_TypeContent");
        lblUpload.Text = ResourceHelper.Get("LBL_UploadFile");
        lblUploadedFile.Text = ResourceHelper.Get("LBL_UploadedFile");
        lblUrl.Text = ResourceHelper.Get("LBL_TypeUrl");
        rfvUrl.ErrorMessage = string.Format(ResourceHelper.Get("MSG_Mandatory"), ResourceHelper.Get("LBL_Url"));
        rfvContent.ErrorMessage = string.Format(ResourceHelper.Get("MSG_Mandatory"), ResourceHelper.Get("LBL_Content"));
        rfvUpload.ErrorMessage = ResourceHelper.Get("MSG_UploadMan");
        rbContent.GroupName = "ftype";
        rbUpload.GroupName = "ftype";
        rbUrl.GroupName = "ftype";
        PopuplateControls();
    }

    public override void AddJavascript()
    {
        try
        {
            LoadJavascript("Javascripts/Settings.js");
            divJavascript.Visible = true;
            divJavascript.InnerHtml += JavascriptText;
        }
        catch (Exception exc)
        { }
    }
    public string FormatBytes(double bytes)
    {
        const int scale = 1024;

        string[] orders = new string[] { "GB", "MB", "KB", "Bytes" };
        double max = (double)Math.Pow(scale, orders.Length - 1);

        foreach (string order in orders)
        {
            if (bytes > max)
                return string.Format("{0:##.##} {1}", Decimal.Divide((decimal)bytes, (decimal)max), order);

            max /= scale;
        }
        return "0 Bytes";
    }
    string GetUploadFileList(List<EventFileType> fileTypes)
    {
        Dictionary<string, string> fts = new Dictionary<string, string>();
        string ftList = "<ul style=\"list-style-type: circle;\">";
        foreach (EventFileType ft in fileTypes)
        {
            ftList += "<li style=\"display: inline;padding-left: 30px;\">" + ft.ToString() + "</li>";
        }
        ftList += "</ul>";
        return ftList;
    }
    List<object> UploadFile()
    {
        List<EventFileType> fTypes = (List<EventFileType>)Session["ALLOWEDFILES"];
        return UploadFile(fTypes);
    }
    List<object> UploadFile(List<EventFileType> fileTypes)
    {
        List<object> retValue = new List<object>();
        int id = MathFunction.ConvertToInteger(Request.QueryString["id"]);
        if (fileNom.HasFile)
        {
            HttpPostedFile file = (HttpPostedFile)(fileNom.PostedFile);
            retValue.Add(file.FileName);

            if ((file != null) && (file.ContentLength > 0))
            {
                EventFileType fType = EventFileType.None;
                if (!IsEventFileType(file, fileTypes, out fType))
                    throw new Exception(string.Format(ResourceHelper.Get("MSG_Nom_FileTypeError"), ResourceHelper.Get("LBL_AllowedFiles") + " :<br/>" + GetUploadFileList(fileTypes)));
                retValue.Add(fType);
            }
            int maxUploadSize = MathFunction.ConvertToInteger(ConfigurationManager.AppSettings["MaxUploadSize"], 2000000);
            int iFileSize = file.ContentLength;

            if (iFileSize > maxUploadSize)
            {
                throw new Exception(string.Format(ResourceHelper.Get("MSG_Nom_FileSizeError"), FormatBytes(maxUploadSize)));
            }

            string filetext = file.FileName;
            string file_ext = System.IO.Path.GetExtension(file.FileName);

            string filename = id.ToString() + "_" + ((int)((TimeSpan)DateTime.Now.Subtract(DateTime.Today)).TotalMilliseconds).ToString().Replace("/", "").Replace("\\", "") + file_ext;
            retValue.Add(filename);

            string filepath = Server.MapPath(ConfigurationManager.AppSettings.Get("NominationFile") + filename);
            retValue.Add(filepath);

            file.SaveAs(filepath);

            if (IsImageType(file))
                ImageProcessor.ResizeImage(filepath, Server.MapPath(ConfigurationManager.AppSettings.Get("NominationThumb") + filename),
                    45, 65, true);

            return retValue;
        }
        return null;
    }
    private bool IsImageType(HttpPostedFile file)
    {
        if ((file == null) || (file.ContentLength <= 0))
            return false;
        return System.Text.RegularExpressions.Regex.IsMatch(file.ContentType, "image/\\S+");
    }
    private bool IsEventFileType(HttpPostedFile file, List<EventFileType> fileTypes, out EventFileType fileType)
    {
        fileType = EventFileType.None;
        MediaType mType = MediaType.None;
        if ((file == null) || (file.ContentLength <= 0))
            return false;
        string filetext = file.FileName;
        string file_ext = System.IO.Path.GetExtension(file.FileName).Substring(1);

        foreach (EventFileType ft in fileTypes)
        {
            switch (ft)
            {
                case EventFileType.Image:
                    mType = MediaType.Image;
                    break;
                case EventFileType.Audio:
                    mType = MediaType.Audio;
                    break;
                case EventFileType.Video:
                    mType = MediaType.Video;
                    break;
                default:
                    mType = MediaType.None;
                    break;
            }
            if (mType != MediaType.None)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(file.ContentType, mType.ToString().ToLower() + "/\\S+"))
                {
                    fileType = (EventFileType)Enum.Parse(typeof(EventFileType), mType.ToString());
                    return true;
                }
                else if (MediaHelper.IsMediaTypeSupported(file_ext, mType))
                {
                    fileType = (EventFileType)Enum.Parse(typeof(EventFileType), mType.ToString());
                    return true;
                }
            }
        }
        return false;
    }
    public override void Init()
    {
        trContent.Visible = false;
        trUpload.Visible = false;
        trUrl.Visible = false;
        if (Session["ALLOWEDFILES"] == null || ((List<EventFileType>)Session["ALLOWEDFILES"]).Count == 0)
            trContent.Visible = true;
        else
        {
            List<EventFileType> fTypes = (List<EventFileType>)Session["ALLOWEDFILES"];
            foreach (EventFileType fType in fTypes)
            {
                switch (fType)
                {
                    case EventFileType.Image:
                    case EventFileType.Audio:
                    case EventFileType.Video:
                        trUpload.Visible = true;
                        lblUploadInfo.Text = ResourceHelper.Get("LBL_AllowedFiles") + "<br/>" + GetUploadFileList(fTypes);
                        lblUploadInfo.Visible = true;
                        break;
                    case EventFileType.Text:
                        trContent.Visible = true;
                        break;
                    case EventFileType.Links:
                        trUrl.Visible = true;
                        break;
                }
            }
        }
        Session["CONTYPE"] = "";
        if (trUpload.Visible && !trUrl.Visible && !trContent.Visible)
        {
            Session["CONTYPE"] = "Upload";
            rbUpload.Visible = false;
        }
        if (!trUpload.Visible && !trUrl.Visible && trContent.Visible)
        {
            Session["CONTYPE"] = "Content";
            rbContent.Visible = false;
        }
        if (!trUpload.Visible && trUrl.Visible && !trContent.Visible)
        {
            Session["CONTYPE"] = "Url";
            rbUrl.Visible = false;
        }

        foreach (string key in Values.Keys)
        {
            if (Values[key] == null)
                continue;
            switch (key)
            {
                case NominationProperty.FileName:
                    // Client file name is different from Server file name.
                    // Server file name need not be shown on UI
                    break;
                case NominationProperty.Type:
                    EventFileType fType = (EventFileType)Enum.Parse(typeof(EventFileType), Values[key].ToString());
                    if (fType != EventFileType.None)
                    {
                        switch (fType)
                        {
                            case EventFileType.Image:
                            case EventFileType.Audio:
                            case EventFileType.Video:
                                rbUpload.Checked = true;
                                break;
                            case EventFileType.Text:
                                rbContent.Checked = true;
                                break;
                            case EventFileType.Links:
                                rbUrl.Checked = true;
                                break;
                        }
                    }
                    break;
                case NominationProperty.TextContent:
                    // Process it out of Foreach loop as is dependent on Type
                    break;
                default:
                    break;
            }
        }
        if (Values.ContainsKey(NominationProperty.TextContent))
        {
            if (rbUrl.Checked)
                txtUrl.Text = Values[NominationProperty.TextContent].ToString();
            else
                txtContent.Text = Values[NominationProperty.TextContent].ToString();
        }
        // Client file name is stored in Session
        if (Session["FILE"] != null)
        {
            lblFilePath.Text = StringHelper.RestrictMaxChar(Session["FILE"].ToString(), 25, EllipseDirection.Begin);
        }
        trFilePath.Visible = (lblFilePath.Text != "");
    }
    public override void SetEvents()
    {

        if (rbContent.Visible)
        {
            rbContent.Attributes.Add("onclick", "javascript:if(document.getElementById('" + rbContent.ClientID + "').checked && !document.getElementById('" + rbContent.ClientID + "').disabled) " +
                "{ SetDisabled(document.getElementById('" + txtContent.ClientID + "'), false); " +
                "SetDisabled(document.getElementById('" + txtUrl.ClientID + "'),true); " +
                "SetDisabled(document.getElementById('" + fileNom.ClientID + "'),true); " +
                "_ValidatorEnable(document.getElementById('" + rfvContent.ClientID + "'),true); " +
                "_ValidatorEnable(document.getElementById('" + rfvUrl.ClientID + "'),false); " +
                "_ValidatorEnable(document.getElementById('" + rfvUpload.ClientID + "'),false); " +
                "}");

            rbContent.Checked = true;
            OnLoadDisable(new string[] { fileNom.ClientID });
            OnLoadDisable(new string[] { txtUrl.ClientID });
            OnLoadExecute(new string[] { "_ValidatorEnable(document.getElementById('" + rfvUrl.ClientID + "'),false)" });
            OnLoadExecute(new string[] { "_ValidatorEnable(document.getElementById('" + rfvUpload.ClientID + "'),false)" });
        }
        if (rbUrl.Visible)
        {
            rbUrl.Attributes.Add("onclick", "javascript:if(document.getElementById('" + rbUrl.ClientID + "').checked && !document.getElementById('" + rbUrl.ClientID + "').disabled) " +
                "{ SetDisabled(document.getElementById('" + txtUrl.ClientID + "'), false); " +
                "SetDisabled(document.getElementById('" + txtContent.ClientID + "'),true); " +
                "SetDisabled(document.getElementById('" + fileNom.ClientID + "'),true); " +
                "_ValidatorEnable(document.getElementById('" + rfvContent.ClientID + "'),false); " +
                "_ValidatorEnable(document.getElementById('" + rfvUrl.ClientID + "'),true); " +
                "_ValidatorEnable(document.getElementById('" + rfvUpload.ClientID + "'),false); " +
                "}");
            if (!rbContent.Checked)
            {
                rbUrl.Checked = true;
                OnLoadDisable(new string[] { fileNom.ClientID });
                OnLoadDisable(new string[] { txtContent.ClientID });
                OnLoadExecute(new string[] { "_ValidatorEnable(document.getElementById('" + rfvContent.ClientID + "'),false)" });
                OnLoadExecute(new string[] { "_ValidatorEnable(document.getElementById('" + rfvUpload.ClientID + "'),false)" });
            }
        }
        if (rbUpload.Visible)
        {
            rbUpload.Attributes.Add("onclick", "javascript:if(document.getElementById('" + rbUpload.ClientID + "').checked && !document.getElementById('" + rbUpload.ClientID + "').disabled) " +
                "{ SetDisabled(document.getElementById('" + fileNom.ClientID + "'),false); " +
                "SetDisabled(document.getElementById('" + txtUrl.ClientID + "'),true); " +
                "SetDisabled(document.getElementById('" + txtContent.ClientID + "'),true); " +
                "_ValidatorEnable(document.getElementById('" + rfvContent.ClientID + "'),false); " +
                "_ValidatorEnable(document.getElementById('" + rfvUrl.ClientID + "'),false); " +
                "_ValidatorEnable(document.getElementById('" + rfvUpload.ClientID + "'),true); " +
                "}");
            if (!rbContent.Checked && !rbUrl.Checked)
            {
                rbUpload.Checked = true;
                OnLoadDisable(new string[] { txtContent.ClientID });
                OnLoadDisable(new string[] { txtUrl.ClientID });
                OnLoadExecute(new string[] { "_ValidatorEnable(document.getElementById('" + rfvContent.ClientID + "'),false)" });
                OnLoadExecute(new string[] { "_ValidatorEnable(document.getElementById('" + rfvUrl.ClientID + "'),false)" });
            }
        }
    }
    public void PopuplateControls() { }
    public override void Dispose()
    {
        //throw new Exception("The method or operation is not implemented.");
    }
    public override Dictionary<string, object> GetValues()
    {
        Dictionary<string, object> retValue = new Dictionary<string, object>();
        if (rbUpload.Checked || Session["CONTYPE"].ToString() == "Upload")
        {
            List<object> file;
            try
            {
                file = UploadFile();
            }
            catch (Exception exc)
            {
                Exception ex = new Exception("File could not be uploaded.");
                ex.Data.Add("UploadInfo", exc.Message);
                throw ex;
            }
            if (file != null && file.Count == 4)
            {
                Session["FILE"] = file[0];
                retValue.Add(NominationProperty.Type, file[1]);
                retValue.Add(NominationProperty.FileName, file[2]);
                if (file[3] != null && file[3].ToString() != "" && (EventFileType)retValue[NominationProperty.Type] == EventFileType.Image)
                {
                    System.Drawing.Image img = System.Drawing.Image.FromFile(file[3].ToString());
                    retValue.Add(NominationProperty.Height, img.Height);
                    retValue.Add(NominationProperty.Width, img.Width);
                }
            }
        }
        else if (rbUrl.Checked || Session["CONTYPE"].ToString() == "Url")
        {
            retValue.Add(NominationProperty.FileName, txtUrl.Text);
            retValue.Add(NominationProperty.Type, EventFileType.Links);
        }
        else
        {
            retValue.Add(NominationProperty.TextContent, HttpUtility.HtmlEncode(txtContent.Text));
            retValue.Add(NominationProperty.Type, EventFileType.Text);
        }
        Session["CONTYPE"] = null;
        Session["FILE"] = null;
        Session["ALLOWEDFILES"] = null;
        return retValue;
    }
}
